/* eslint-disable no-unused-vars */
var http = require('http')
var spawn = require('child_process').spawn
const crypto = require('crypto')
var querystring = require('querystring')

// 脚本地址
const script = 'robot.bat'
// 执行指令的地址
// const currentPath = 'D:\\code\\work2\\git\\hy-english'
const currentPath = 'D:\\wwwroot\\huoyan\\hy-english'
const password = '123456'
http
  .createServer(function(req, res) {
    console.log(JSON.stringify(req.headers))
    var giteeToken = req.headers['x-gitee-token'] || ''
    var giteeTimestamp = req.headers['x-gitee-timestamp'] || ''
    var source = giteeTimestamp + '\n' + password
    var cipher = crypto
      .createHmac('SHA256', password)
      .update(source)
      .digest('base64')
    var cipher2 = encodeURI(cipher)

    if (giteeToken === cipher2) {
      var post = ''
      // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
      // 当有数据请求时触发
      req.on('data', function(data) {
        post += data
      })
      // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
      req.on('end', function() {
        // 解析为post对象
        var data = JSON.parse(post)
        if (
          data &&
          data.repository &&
          data.repository.default_branch &&
          data.repository.default_branch === 'master'
        ) {
          rumCommand(script, null, function(txt) {
            console.log(`在${currentPath}目录下执行了脚本${script}`)
            res.statusCode = 200
            res.end(txt)
          })
        }
        res.statusCode = 200
        res.end('success')
      })
    } else {
      // rumCommand(script, null, function(txt) {
      //   console.log(`在${currentPath}目录下执行了脚本${script}`)
      //   console.log(txt)
      //   res.statusCode = 200
      //   res.end(txt)
      // })
      // res.statusCode = 200
      // res.end('??')
    }
  })
  .listen(process.env.PORT || 3000)

function rumCommand(cmd, args, callback) {
  var child = spawn(cmd, args, {
    cwd: currentPath
  })
  var response = ''
  child.stdout.on('data', function(buffer) {
    response += buffer.toString()
  })
  child.stdout.on('end', function() {
    callback(response)
  })
  child.on('exit', function(code) {
    console.log(code)
  })
  child.stderr.on('data', function(data) {
    console.log('stderr: ' + data)
  })
}
